import React, { useMemo, useState } from 'react';
import { 
  Table, 
  Tag, 
  Typography, 
  Space, 
  Button,
  Tooltip,
  Modal,
  Row,
  Col,
  Select,
  Card,
  Alert
} from 'antd';
import RuleDetailModal from './RuleDetailModal';
import { 
  EyeOutlined,
  BulbOutlined,
  RobotOutlined,
  GitlabOutlined,
  GithubOutlined,
  LinkOutlined,
  DatabaseOutlined,
  FileTextOutlined,
  FilterOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { UnifiedProblemData } from '../../types/analysis';
import './ProblemTable.css';

const { Text, Paragraph } = Typography;
const { Option } = Select;

// AI置信度阈值常量
const AI_CONFIDENCE_THRESHOLD = 0.7; // >=0.7为确认，<0.7为质疑

interface EnhancedProblemTableProps {
  problems: UnifiedProblemData[];
  selectedIssueId?: string | null;
  onIssueClick?: (issue: UnifiedProblemData) => void;
  onApplySuggestion?: (issue: UnifiedProblemData) => void;
  onBatchApply?: (issues: UnifiedProblemData[]) => void;
  height?: number;
  taskConfig?: any; // 任务配置信息，用于构建Git链接
}

const EnhancedProblemTable: React.FC<EnhancedProblemTableProps> = ({
  problems,
  selectedIssueId,
  onIssueClick,
  onApplySuggestion,
  onBatchApply,
  height = 400,
  taskConfig
}) => {
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedProblem, setSelectedProblem] = useState<UnifiedProblemData | null>(null);
  
  // 筛选状态
  const [filters, setFilters] = useState({
    severity: 'ALL',
    aiConfirmation: 'ALL'
  });
  
  // 规则详情模态框状态
  const [ruleDetailVisible, setRuleDetailVisible] = useState(false);
  const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null);

  // 过滤后的问题列表
  const filteredProblems = useMemo(() => {
    return problems.filter(problem => {
      // 严重程度筛选
      if (filters.severity !== 'ALL' && problem.severity !== filters.severity) {
        return false;
      }

      // AI确认状态筛选 - 基于aiOptimized和置信度
      if (filters.aiConfirmation !== 'ALL') {
        switch (filters.aiConfirmation) {
          case 'AI_CONFIRMED':
            // 经过AI验证且置信度高（>= AI_CONFIDENCE_THRESHOLD表示确认）
            return problem.aiOptimized === true && (problem.aiConfidenceScore ?? 0) >= AI_CONFIDENCE_THRESHOLD;
          case 'AI_QUESTIONED':
            // 经过AI验证但置信度低（< AI_CONFIDENCE_THRESHOLD表示质疑）
            return problem.aiOptimized === true && (problem.aiConfidenceScore ?? 0) < AI_CONFIDENCE_THRESHOLD;
          case 'NOT_VERIFIED':
            return !problem.aiOptimized;
          default:
            break;
        }
      }

      return true;
    });
  }, [problems, filters]);

  // 获取严重程度对应的颜色
  const getSeverityColor = (severity: string) => {
    const colors = {
      'HIGH': '#ff4d4f',      // 红色 - 高危
      'MEDIUM': '#faad14',    // 橙色 - 中危  
      'LOW': '#1890ff',       // 蓝色 - 低危
      'INFO': '#52c41a'       // 绿色 - 提示
    };
    return colors[severity as keyof typeof colors] || '#666666';
  };

  // 获取严重程度标签
  const getSeverityTag = (severity: string) => {
    const configs = {
      'HIGH': { color: 'error', text: '高危' },
      'MEDIUM': { color: 'warning', text: '中危' },
      'LOW': { color: 'processing', text: '低危' },
      'INFO': { color: 'success', text: '提示' }
    };
    const config = configs[severity as keyof typeof configs] || { color: 'default', text: severity };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取分类标签
  const getCategoryLabel = (category: string) => {
    const labels = {
      'SYNTAX': '语法',
      'FUNCTION': '函数',
      'DATATYPE': '数据类型',
      'PERFORMANCE': '性能',
      'COMPATIBILITY': '兼容性'
    };
    return labels[category as keyof typeof labels] || category;
  };


  // 辅助函数：获取Git平台图标
  const getGitPlatformIcon = (gitUrl: string): React.ReactNode => {
    if (!gitUrl) return <LinkOutlined />;
    
    if (gitUrl.includes('gitlab')) {
      return <GitlabOutlined style={{ color: '#FC6D26' }} />;
    } else if (gitUrl.includes('github')) {
      return <GithubOutlined style={{ color: '#181717' }} />;
    } else if (gitUrl.includes('gitee')) {
      return <GithubOutlined style={{ color: '#C71D23' }} />;
    }
    return <LinkOutlined />;
  };

  // 简化的SQL语法高亮函数
  const highlightSql = (sql: string) => {
    if (!sql) return '';
    
    // 对HTML特殊字符进行转义
    let escaped = sql
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
    
    // 基本的SQL关键字高亮（避免复杂的正则表达式）
    const keywords = [
      'SELECT', 'FROM', 'WHERE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'OUTER', 
      'ON', 'AND', 'OR', 'ORDER', 'BY', 'GROUP', 'HAVING', 'INSERT', 'UPDATE', 
      'DELETE', 'CREATE', 'DROP', 'ALTER', 'TABLE', 'INDEX', 'VIEW', 'INTO', 
      'VALUES', 'SET', 'DISTINCT', 'AS', 'ASC', 'DESC', 'LIMIT', 'OFFSET', 
      'UNION', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'IF', 'NULL', 'NOT', 
      'IS', 'IN', 'LIKE', 'BETWEEN', 'EXISTS', 'COUNT', 'SUM', 'AVG', 'MAX', 
      'MIN', 'ROWNUM', 'NVL2', 'NULLS', 'LAST', 'CONSTRAINT', 'PRIMARY', 
      'KEY', 'FOREIGN', 'REFERENCES', 'ENGINE', 'CHARSET', 'AUTO_INCREMENT', 
      'DEFAULT', 'BIGINT', 'VARCHAR', 'DECIMAL', 'DATETIME'
    ];
    
    // 简单的关键字高亮（只处理完整单词）
    keywords.forEach(keyword => {
      const regex = new RegExp(`\\b${keyword}\\b`, 'gi');
      escaped = escaped.replace(regex, `<span style="color: #1890ff; font-weight: bold;">${keyword.toUpperCase()}</span>`);
    });
    
    return escaped;
  };

  // 处理查看详情
  const handleViewDetail = (problem: UnifiedProblemData) => {
    setSelectedProblem(problem);
    setDetailModalVisible(true);
  };

  // 处理应用建议
  // 处理规则名称点击
  const handleRuleNameClick = (ruleId: string | undefined, event: React.MouseEvent) => {
    event.stopPropagation(); // 阻止行点击事件
    if (ruleId && ruleId !== 'AI001' && !ruleId.startsWith('AI')) {
      setSelectedRuleId(ruleId);
      setRuleDetailVisible(true);
    }
  };

  // 关闭规则详情模态框
  const handleRuleDetailClose = () => {
    setRuleDetailVisible(false);
    setSelectedRuleId(null);
  };

  // 表格列定义
  const columns: ColumnsType<UnifiedProblemData> = [
    {
      title: 'SQL#',
      dataIndex: 'statementNumber',
      key: 'statementNumber',
      width: 70,
      fixed: 'left',
      render: (statementNumber: number) => (
        <Tag 
          color="blue" 
          style={{ 
            fontFamily: 'monospace', 
            fontSize: '12px',
            fontWeight: 'bold',
            minWidth: '40px',
            textAlign: 'center'
          }}
        >
          #{statementNumber}
        </Tag>
      ),
      sorter: (a, b) => a.statementNumber - b.statementNumber
    },

    {
      title: '问题名称',
      dataIndex: 'ruleName',
      key: 'ruleName', 
      width: 180,
      ellipsis: { showTitle: false },
      render: (ruleName: string, record) => {
        const severityColor = getSeverityColor(record.severity);
        const hasRuleId = record.ruleId && record.ruleId !== 'AI001' && !record.ruleId.startsWith('AI');
        
        return (
          <Tooltip title={`${record.description} (规则ID: ${record.ruleId})`} placement="topLeft">
            <div style={{ 
              display: 'flex', 
              alignItems: 'flex-start',
              gap: '6px'
            }}>
              {record.analysisSource === 'LLM' && (
                <Tag color="purple" style={{ fontSize: '10px' }}>
                  AI
                </Tag>
              )}
              
              {hasRuleId ? (
                <Button
                  type="link"
                  onClick={(e) => handleRuleNameClick(record.ruleId, e)}
                  style={{ 
                    padding: 0,
                    height: 'auto',
                    color: severityColor, 
                    fontSize: '13px',
                    lineHeight: '1.4',
                    fontWeight: '500',
                    textAlign: 'left',
                    whiteSpace: 'normal',
                    wordBreak: 'break-word',
                    border: 'none',
                    background: 'none',
                    transition: 'all 0.2s ease'
                  }}
                  className="rule-name-clickable"
                >
                  {ruleName}
                </Button>
              ) : (
                <Text style={{ 
                  color: severityColor, 
                  fontSize: '13px',
                  lineHeight: '1.4',
                  fontWeight: '500'
                }}>
                  {ruleName}
                </Text>
              )}
            </div>
          </Tooltip>
        );
      },
      sorter: (a, b) => {
        // 先按严重程度排序，再按问题名称排序
        const severityOrder = { HIGH: 4, MEDIUM: 3, LOW: 2, INFO: 1 };
        const severityDiff = (severityOrder[a.severity as keyof typeof severityOrder] || 0) - 
                            (severityOrder[b.severity as keyof typeof severityOrder] || 0);
        if (severityDiff !== 0) return severityDiff;
        return (a.ruleName || '').localeCompare(b.ruleName || '');
      },
      defaultSortOrder: 'descend'
    },

    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      width: 80,
      render: (severity: string) => getSeverityTag(severity),
      sorter: (a, b) => {
        const severityOrder = { HIGH: 4, MEDIUM: 3, LOW: 2, INFO: 1 };
        return (severityOrder[b.severity as keyof typeof severityOrder] || 0) - 
               (severityOrder[a.severity as keyof typeof severityOrder] || 0);
      }
    },

    {
      title: 'AI验证',
      key: 'aiVerification',
      width: 70,
      render: (_, record) => {
        const isAiVerified = record.aiOptimized === true;
        const confidenceScore = record.aiConfidenceScore ?? 0;
        const isConfirmedByAI = confidenceScore >= AI_CONFIDENCE_THRESHOLD; // 使用常量替代魔法数字
        
        if (!isAiVerified) {
          return (
            <Tag color="default" style={{ fontSize: '10px', textAlign: 'center' }}>
              未验证
            </Tag>
          );
        }
        
        return (
          <Tooltip title={
            isConfirmedByAI 
              ? `AI确认此问题确实存在 (置信度: ${Math.round(confidenceScore * 100)}%)` 
              : `AI质疑此问题的重要性 (置信度: ${Math.round(confidenceScore * 100)}%)`
          }>
            <Tag 
              color={isConfirmedByAI ? 'red' : 'cyan'} 
              style={{ fontSize: '10px', margin: 0, width: '100%', textAlign: 'center' }}
            >
              {isConfirmedByAI ? 'AI确认' : 'AI质疑'}
            </Tag>
          </Tooltip>
        );
      },
      sorter: (a, b) => {
        // 按AI确认状态排序：确认 > 质疑 > 未验证
        const getValue = (record: UnifiedProblemData) => {
          if (!record.aiOptimized) return 1; // 未验证
          const confidenceScore = record.aiConfidenceScore ?? 0;
          if (confidenceScore >= AI_CONFIDENCE_THRESHOLD) return 3; // AI确认（置信度>=阈值）
          return 2; // AI质疑（置信度<0.7）
        };
        return getValue(b) - getValue(a);
      }
    },

    {
      title: '问题SQL片段',
      dataIndex: 'sqlFragment',
      key: 'sqlFragment',
      width: 140,
      ellipsis: { showTitle: false },
      render: (sqlFragment: string, record) => {
        const displayCode = sqlFragment || record.originalCode;
        
        return displayCode ? (
          <Tooltip title={displayCode} placement="topLeft">
            <div className="sql-fragment-container problem-fragment">
              <Text 
                style={{
                  fontFamily: 'monospace',
                  fontSize: '11px',
                  color: '#666',
                  display: 'block',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap'
                }}
              >
                {displayCode.substring(0, 30)}...
              </Text>
            </div>
          </Tooltip>
        ) : (
          <Text type="secondary" style={{ fontSize: '12px' }}>无片段</Text>
        );
      }
    },

    {
      title: '修改建议',
      dataIndex: 'suggestion',
      key: 'suggestion',
      width: 160,
      ellipsis: { showTitle: false },
      render: (suggestion: string) => (
        suggestion ? (
          <Tooltip title={suggestion} placement="topLeft">
            <Text style={{ 
              color: '#52c41a', 
              fontSize: '12px',
              display: 'block',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap'
            }}>
              {suggestion.substring(0, 25)}...
            </Text>
          </Tooltip>
        ) : (
          <Text type="secondary">-</Text>
        )
      )
    },

    {
      title: 'SQL来源',
      key: 'sqlSource',
      width: 110,
      ellipsis: { showTitle: false },
      render: (_, record) => {
        // 直接使用接口返回的gitFileUrl，无需前端拼接
        const gitFileUrl = record.gitFileUrl;
        const gitRepositoryUrl = taskConfig?.gitRepositoryUrl || taskConfig?.repositoryUrl;
        const fileName = record.fileName ? record.fileName.split('/').pop() : null;
        
        if (gitFileUrl && fileName) {
          // Git源码扫描 - 紧凑显示
          return (
            <Tooltip title={`在Git平台中查看文件 (行 ${record.lineNumber})`}>
              <Button
                type="link"
                size="small"
                icon={getGitPlatformIcon(gitRepositoryUrl)}
                onClick={() => window.open(gitFileUrl, '_blank')}
                style={{ 
                  padding: '0 2px', 
                  height: 'auto', 
                  fontSize: '11px',
                  display: 'flex',
                  alignItems: 'center',
                  color: '#1890ff',
                  fontWeight: '500'
                }}
                className="git-link-enhanced"
              >
                <Text ellipsis style={{ maxWidth: 80, fontSize: '11px' }}>
                  {fileName}:{record.lineNumber}
                </Text>
              </Button>
            </Tooltip>
          );
        } else if (fileName) {
          // 有文件名但无Git链接
          return (
            <Space size={4} style={{ fontSize: '11px' }}>
              <FileTextOutlined style={{ color: '#8c8c8c', fontSize: 11 }} />
              <Text ellipsis style={{ maxWidth: 80, fontSize: '11px' }}>
                {fileName}:{record.lineNumber}
              </Text>
            </Space>
          );
        } else {
          // 数据库扫描或手动SQL
          if (taskConfig?.taskType === 'DATABASE_DDL_SCAN') {
            return (
              <Space size={4} style={{ fontSize: '11px' }}>
                <DatabaseOutlined style={{ color: '#fa8c16', fontSize: 11 }} />
                <Text style={{ fontSize: '11px', color: '#fa8c16' }}>数据库</Text>
              </Space>
            );
          } else if (taskConfig?.taskType === 'MANUAL_SQL') {
            return (
              <Space size={4} style={{ fontSize: '11px' }}>
                <FileTextOutlined style={{ color: '#722ed1', fontSize: 11 }} />
                <Text style={{ fontSize: '11px', color: '#722ed1' }}>手动</Text>
              </Space>
            );
          } else {
            return (
              <Text type="secondary" style={{ fontSize: '11px' }}>未知</Text>
            );
          }
        }
      }
    },

    {
      title: '操作',
      key: 'actions',
      width: 60,
      fixed: 'right',
      render: (_, record) => (
        <Tooltip title="查看详情">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              handleViewDetail(record);
            }}
            style={{ padding: '4px' }}
          />
        </Tooltip>
      )
    }
  ];

  return (
    <div className="problem-table enhanced-problem-table">
      {/* 筛选器区域 */}
      <Card 
        size="small" 
        style={{ marginBottom: 16, background: '#fafafa' }}
        bodyStyle={{ padding: '12px 16px' }}
      >
        <Row gutter={16} align="middle">
          <Col>
            <Space align="center">
              <FilterOutlined style={{ color: '#1890ff' }} />
              <Text strong style={{ color: '#1890ff', fontSize: '13px' }}>筛选条件</Text>
            </Space>
          </Col>
          <Col>
            <Space align="center" size={8}>
              <Text style={{ fontSize: '12px' }}>严重程度:</Text>
              <Select
                value={filters.severity}
                onChange={(value) => setFilters(prev => ({ ...prev, severity: value }))}
                size="small"
                style={{ width: 100 }}
              >
                <Option value="ALL">全部</Option>
                <Option value="HIGH">高危</Option>
                <Option value="MEDIUM">中危</Option>
                <Option value="LOW">低危</Option>
                <Option value="INFO">提示</Option>
              </Select>
            </Space>
          </Col>
          <Col>
            <Space align="center" size={8}>
              <Text style={{ fontSize: '12px' }}>AI验证:</Text>
              <Select
                value={filters.aiConfirmation}
                onChange={(value) => setFilters(prev => ({ ...prev, aiConfirmation: value }))}
                size="small"
                style={{ width: 100 }}
              >
                <Option value="ALL">全部</Option>
                <Option value="AI_CONFIRMED">AI确认</Option>
                <Option value="AI_QUESTIONED">AI质疑</Option>
                <Option value="NOT_VERIFIED">未验证</Option>
              </Select>
            </Space>
          </Col>
          <Col>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              共 {filteredProblems.length} / {problems.length} 个问题
            </Text>
          </Col>
        </Row>
      </Card>

      {/* AI验证提示 */}
      <Alert
        message={
          <Space>
            <InfoCircleOutlined />
            <Text style={{ fontSize: '13px' }}>
              <Text strong>提示：</Text>
              针对AI验证的问题，可以点击操作列的
              <EyeOutlined style={{ margin: '0 4px', color: '#1890ff' }} />
              查看详情，在弹窗中查看AI优化后的SQL语句。
            </Text>
          </Space>
        }
        type="info"
        showIcon={false}
        style={{ 
          marginBottom: 16, 
          background: 'linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%)',
          border: '1px solid #91d5ff'
        }}
        closable
      />
      
      <Table
        columns={columns}
        dataSource={filteredProblems}
        rowKey="id"
        size="small"
        scroll={{ 
          y: 500, // 调整为能显示10行数据的高度，无滚动条
          x: 970
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: ['10', '25', '50', '100'],
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
          size: 'default'
        }}
        rowClassName={(record) => {
          const baseClass = selectedIssueId === record.id ? 'problem-row-selected' : 'problem-row';
          const sourceClass = record.analysisSource === 'LLM' ? 'problem-row-ai' : 'problem-row-rule';
          return `${baseClass} ${sourceClass}`;
        }}
        onRow={(record) => ({
          onClick: () => onIssueClick?.(record),
          style: { cursor: 'pointer' }
        })}
      />

      {/* 问题详情弹窗 */}
      <Modal
        title={
          <Space>
            <span>问题详情</span>
            {selectedProblem && getSeverityTag(selectedProblem.severity)}
            {selectedProblem?.analysisSource === 'LLM' && (
              <Tag color="purple">
                <RobotOutlined /> AI分析
              </Tag>
            )}
            {/* AI验证状态显示 */}
            {selectedProblem && selectedProblem.aiOptimized && (
              <Tag color={(selectedProblem.aiConfidenceScore ?? 0) >= AI_CONFIDENCE_THRESHOLD ? 'red' : 'cyan'}>
                {(selectedProblem.aiConfidenceScore ?? 0) >= AI_CONFIDENCE_THRESHOLD ? 'AI确认问题' : 'AI质疑问题'}
              </Tag>
            )}
          </Space>
        }
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedProblem && (
          <div className="problem-detail">
            {/* 基本信息区域 */}
            <div className="detail-section" style={{ background: '#fafafa', padding: '12px', borderRadius: '6px', marginBottom: '16px' }}>
              <Row gutter={[16, 8]}>
                <Col span={8}>
                  <Text strong style={{ color: '#1890ff' }}>SQL语句编号</Text>
                  <div style={{ marginTop: 4 }}>
                    <Tag color="blue" style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                      #{selectedProblem.statementNumber}
                    </Tag>
                  </div>
                </Col>
                <Col span={8}>
                  <Text strong style={{ color: '#1890ff' }}>问题分类</Text>
                  <div style={{ marginTop: 4 }}>
                    <Tag color="blue">{getCategoryLabel(selectedProblem.category)}</Tag>
                  </div>
                </Col>
                <Col span={8}>
                  <Text strong style={{ color: '#1890ff' }}>分析来源</Text>
                  <div style={{ marginTop: 4 }}>
                    <Tag 
                      color={selectedProblem.analysisSource === 'LLM' ? 'purple' : 'blue'}
                      icon={selectedProblem.analysisSource === 'LLM' ? <RobotOutlined /> : undefined}
                    >
                      {selectedProblem.analysisSource === 'LLM' ? 'AI分析' : '规则分析'}
                    </Tag>
                  </div>
                </Col>
              </Row>
            </div>

            {/* AI验证状态区域 */}
            {selectedProblem.aiOptimized && (
              <div className="detail-section" style={{ 
                background: selectedProblem.ruleAnalysisConfirmed ? '#fff2f0' : '#e6fffb', 
                padding: '12px', 
                borderRadius: '6px', 
                marginBottom: '16px',
                border: `1px solid ${selectedProblem.ruleAnalysisConfirmed ? '#ffccc7' : '#87e8de'}`
              }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                  <RobotOutlined style={{ color: '#722ed1', marginRight: 8, fontSize: '16px' }} />
                  <Text strong style={{ color: '#722ed1', fontSize: '14px' }}>AI验证结果</Text>
                </div>
                <Row gutter={[16, 8]}>
                  <Col span={12}>
                    <Tag 
                      color={(selectedProblem.aiConfidenceScore ?? 0) >= AI_CONFIDENCE_THRESHOLD ? 'red' : 'cyan'}
                      style={{ fontSize: '12px', marginBottom: 8 }}
                    >
                      {(selectedProblem.aiConfidenceScore ?? 0) >= AI_CONFIDENCE_THRESHOLD ? '✓ AI确认此问题确实存在' : '? AI质疑此问题的重要性'}
                    </Tag>
                  </Col>
                  <Col span={12}>
                    <Tag color="blue" style={{ fontSize: '12px' }}>
                      置信度: {Math.round((selectedProblem.aiConfidenceScore ?? 0) * 100)}%
                    </Tag>
                  </Col>
                </Row>
                {selectedProblem.aiIssueDescription && (
                  <div style={{ marginTop: 8, padding: '8px 12px', background: 'rgba(255,255,255,0.7)', borderRadius: '4px' }}>
                    <Text style={{ fontSize: '13px', fontStyle: 'italic' }}>
                      "{selectedProblem.aiIssueDescription}"
                    </Text>
                  </div>
                )}
              </div>
            )}
            
            {/* 问题信息区域 */}
            <div className="detail-section" style={{ marginBottom: '16px' }}>
              {selectedProblem.ruleName && (
                <div style={{ marginBottom: '12px' }}>
                  <Text strong style={{ display: 'block', marginBottom: '4px' }}>问题名称</Text>
                  {selectedProblem.ruleId && selectedProblem.ruleId !== 'AI001' && !selectedProblem.ruleId.startsWith('AI') ? (
                    <Button
                      type="link"
                      size="small"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleRuleNameClick(selectedProblem.ruleId, e);
                      }}
                      style={{ 
                        padding: '4px 8px',
                        fontSize: '13px',
                        fontWeight: '500',
                        background: 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)',
                        color: '#ffffff',
                        borderRadius: '6px',
                        border: 'none'
                      }}
                    >
                      <EyeOutlined style={{ fontSize: '11px', marginRight: '4px' }} />
                      {selectedProblem.ruleName}
                    </Button>
                  ) : (
                    <Text style={{ fontWeight: '500', fontSize: '13px' }}>
                      {selectedProblem.ruleName}
                    </Text>
                  )}
                  {selectedProblem.ruleId && (
                    <Tag 
                      color={selectedProblem.analysisSource === 'LLM' ? 'purple' : 'default'}
                      style={{ fontFamily: 'monospace', fontSize: '11px', marginLeft: '8px' }}
                    >
                      {selectedProblem.ruleId}
                    </Tag>
                  )}
                </div>
              )}
              
              <div style={{ marginBottom: '12px' }}>
                <Text strong style={{ display: 'block', marginBottom: '4px' }}>问题描述</Text>
                <Paragraph style={{ margin: 0, fontSize: '13px', lineHeight: '1.6', color: '#595959' }}>
                  {selectedProblem.description}
                </Paragraph>
              </div>
            </div>
            
            {/* SQL代码区域 */}
            <div className="detail-section" style={{ marginBottom: '16px' }}>
              {(selectedProblem.sqlFragment || selectedProblem.originalCode) && (
                <div style={{ marginBottom: '12px' }}>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>问题SQL片段</Text>
                  <div className="code-block" style={{ background: '#fff6f6', border: '1px solid #ffccc7' }}>
                    <pre style={{ margin: 0, fontSize: '12px' }} dangerouslySetInnerHTML={{ 
                      __html: highlightSql((selectedProblem.sqlFragment || selectedProblem.originalCode) || '') 
                    }} />
                  </div>
                </div>
              )}
              
              {selectedProblem.suggestedCode && (
                <div style={{ marginBottom: '12px' }}>
                  <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                    <BulbOutlined style={{ color: '#52c41a', marginRight: 4 }} />
                    建议修改
                  </Text>
                  <div className="code-block suggested" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                    <pre style={{ margin: 0, fontSize: '12px' }} dangerouslySetInnerHTML={{ 
                      __html: highlightSql(selectedProblem.suggestedCode || '') 
                    }} />
                  </div>
                </div>
              )}
            </div>

            {/* AI优化区域 */}
            {(selectedProblem.optimizedSql || selectedProblem.optimizationExplanation) && (
              <div className="detail-section" style={{ 
                background: '#f9f0ff', 
                padding: '12px', 
                borderRadius: '6px',
                border: '1px solid #d3adf7',
                marginBottom: '16px'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: '12px' }}>
                  <RobotOutlined style={{ color: '#722ed1', marginRight: 8, fontSize: '16px' }} />
                  <Text strong style={{ color: '#722ed1', fontSize: '14px' }}>AI优化建议</Text>
                </div>
                
                {selectedProblem.optimizationExplanation && (
                  <div style={{ marginBottom: '12px' }}>
                    <Text style={{ fontSize: '13px', lineHeight: '1.6', color: '#595959' }}>
                      {selectedProblem.optimizationExplanation}
                    </Text>
                  </div>
                )}
                
                {selectedProblem.optimizedSql && (
                  <div>
                    <Text strong style={{ display: 'block', marginBottom: '8px', color: '#722ed1' }}>
                      优化后SQL
                    </Text>
                    <div className="code-block ai-optimized" style={{ background: '#fff', border: '1px solid #722ed1' }}>
                      <pre style={{ margin: 0, fontSize: '12px' }} dangerouslySetInnerHTML={{ 
                        __html: highlightSql(selectedProblem.optimizedSql || '') 
                      }} />
                    </div>
                  </div>
                )}
              </div>
            )}
            
            {/* 修复建议区域 */}
            {selectedProblem.suggestion && (
              <div className="detail-section" style={{ 
                background: '#f0f9ff', 
                padding: '12px', 
                borderRadius: '6px',
                border: '1px solid #91d5ff'
              }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
                  <BulbOutlined style={{ color: '#1890ff', marginTop: '2px', fontSize: '14px' }} />
                  <div>
                    <Text strong style={{ display: 'block', marginBottom: '4px', color: '#1890ff' }}>修复建议</Text>
                    <Text style={{ fontSize: '13px', lineHeight: '1.6' }}>{selectedProblem.suggestion}</Text>
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* 规则详情模态框 */}
      <RuleDetailModal
        visible={ruleDetailVisible}
        ruleId={selectedRuleId}
        onClose={handleRuleDetailClose}
      />
    </div>
  );
};

export default EnhancedProblemTable;